/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ListaFuncionarios.java
 *
 * Created on May 6, 2009, 11:25:25 PM
 */
package visao;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import negocio.Funcionario;
import persistencia.FuncionarioDAO;

/**
 *
 * @author thiago
 */
public class ListaFuncionarios extends javax.swing.JInternalFrame {

    private List<Funcionario> funcionarios = new ArrayList<Funcionario>();
    private Funcionario funcionario;
    private TabelaModelo<Funcionario> modelo;

    /** Creates new form ListaFuncionarios */
    public ListaFuncionarios() {
        initComponents();
        carregarFuncionarios();
        preencherTabela();
        this.setVisible(true);
        this.setSize(600, 400);
        ControladorDeEventos controlador = new ControladorDeEventos();
        btnAdicionar.addActionListener(controlador);
        btnApagar.addActionListener(controlador);
        btnEditar.addActionListener(controlador);
    }

    private void adicionar() {
        TelaPrincipal.abrirJanela(new CadastroFuncionarios());

        carregarFuncionarios();
        preencherTabela();
    }

    private void apagar() {
        funcionario = modelo.getObjetoSelecionado();

        if (funcionario != null && JOptionPane.showOptionDialog(this, "Deseja excluir o funcionario" + funcionario.getNome() + "?",
                "Cadastro de Funcionários", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, "Sim,Não".split(","), "Sim") == 0) {
            try {
                new FuncionarioDAO().remover(funcionario);
                JOptionPane.showMessageDialog(this, "Funcionários Removido com Sucesso","Remover Funcionário", JOptionPane.INFORMATION_MESSAGE);
                carregarFuncionarios();
                preencherTabela();

            } catch (SQLException ex) {
               ex.printStackTrace();
               JOptionPane.showMessageDialog(this, "Erro ao remover Funcionario", "Remover Funcionário", JOptionPane.ERROR_MESSAGE);
            }


        }

    }

    private List<Funcionario> carregarFuncionarios() {
        try {
            funcionarios.clear();
            funcionarios.addAll(new FuncionarioDAO().listarFuncionario());
            System.out.println("fsdfsdsadsdfds" + funcionarios);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

        return funcionarios;
    }

    private void preencherTabela() {
        String[] colunas = "Código, Nome, CPF, RG, Cargo".split(", ");
        System.out.println(funcionarios);
        modelo = new TabelaModelo<Funcionario>(funcionarios, colunas, tabela) {

            public Object getValueAt(int indiceLinha, int indiceColuna) {
                switch (indiceColuna) {
                    case 0:
                        return linhas.get(indiceLinha).getId();
                    case 1:
                        return linhas.get(indiceLinha).getNome();
                    case 2:
                        return linhas.get(indiceLinha).getCpf();
                    case 3:
                        return linhas.get(indiceLinha).getRg();
                    case 4:
                        return linhas.get(indiceLinha).getCargo();
                    default:
                        return null;
                }
            }

            public boolean isCellEditable(int indiceLinha, int indiceColuna) {
                return indiceColuna == 0 ? false : true;
            }

            public void setValueAt(Object valor, int indiceLinha, int indiceColuna) {
                funcionario = getObjetoPorIndice(indiceLinha);
                String valorString = (String) valor;
                if (funcionario != null) {
                    switch (indiceColuna) {
                        case 0:
                            funcionario.setNome(valorString);
                        case 1:
                            funcionario.setCpf(valorString);
                        case 2:
                            funcionario.setRg(valorString);
                        case 3:
                            funcionario.setCargo(valorString);
                    }

                }
            }
        };

        tabela.getColumn("Código").setPreferredWidth(90);
        tabela.getColumn("Nome").setPreferredWidth(250);
        tabela.getColumn("CPF").setPreferredWidth(100);
        tabela.getColumn("RG").setPreferredWidth(100);
        tabela.getColumn("Cargo").setPreferredWidth(100);



    }

    private class ControladorDeEventos implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            Object origem = e.getSource();

            if (origem == btnAdicionar) {
                adicionar();
            } else if (origem == btnApagar) {
                apagar();
            } else if (origem == btnEditar) {
            }
        }
    }

    public static void main(String args[]) {

        ListaFuncionarios t = new ListaFuncionarios();
        t.setVisible(true);

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        tfPesquisar = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabela = new javax.swing.JTable();
        btnAdicionar = new javax.swing.JButton();
        btnEditar = new javax.swing.JButton();
        btnApagar = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);

        jLabel1.setText("Pesquisar :");

        tabela.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(tabela);

        btnAdicionar.setText("Adicionar");

        btnEditar.setText("Editar");

        btnApagar.setText("Apagar");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addGap(4, 4, 4)
                .addComponent(tfPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 482, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(23, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(160, 160, 160)
                .addComponent(btnAdicionar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnEditar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnApagar)
                .addContainerGap(188, Short.MAX_VALUE))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE)
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAdicionar, btnApagar, btnEditar});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(tfPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 361, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAdicionar)
                    .addComponent(btnEditar)
                    .addComponent(btnApagar))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnAdicionar, btnApagar, btnEditar});

        pack();
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdicionar;
    private javax.swing.JButton btnApagar;
    private javax.swing.JButton btnEditar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tabela;
    private javax.swing.JTextField tfPesquisar;
    // End of variables declaration//GEN-END:variables
}
